// cloudfunctions/searchProducts/index.js
const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  const {
    keyword = '',
    category = '',
    minPrice = 0,
    maxPrice = 999999,
    page = 1,
    pageSize = 20,
	groupId=''
  } = event;
  
  try {
    // 构建查询条件
    const match = {};
    
    // 关键词搜索（模糊匹配）
    if (keyword) {
      match.productName = new RegExp(keyword, 'i');
    }
    
    // 分类筛选
    if (category) {
      match.categorize = category;
    }
	if(groupId){
		match.groupId=groupId
	}
    
    // 价格范围筛选
    match.price = dbCmd.gte(minPrice).lte(maxPrice);
    
    // 查询商品列表
    const products = await db.collection('sendgood')
      .where(match)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();
      
    // 查询总数量
    const total = await db.collection('sendgood')
      .where(match)
      .count();
    
    return {
      success: true,
      data: products.data,
      pagination: {
        page,
        pageSize,
        total: total.total,
        totalPages: Math.ceil(total.total / pageSize)
      }
    };
  } catch (error) {
    console.error('搜索失败:', error);
    return {
      success: false,
      message: '搜索失败，请稍后再试'
    };
  }
};